﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using ActionSystem.Core.Utils;
using ActionSystem.Core;
using ActionSystem.Core.EventSystem;
namespace ActionSystem.Input
{
    /// <summary>
    /// 读取按钮信息或者UI输入
    /// UserInputEventSystem => InputCache => InputModule
    /// </summary>
    public sealed class UserInputEventSystem : NormalSingleton<UserInputEventSystem>, IActionSystemSync
    {
        EventSystem eventSystem=new EventSystem();
        IInputDevice input = null;
        HashSet<int> keys = new HashSet<int>();

        /// <summary>
        /// 设置输入设备
        /// </summary>
        /// <param name="input"></param>
        public void SetInput(IInputDevice input)
        {
            this.input = input;
        }
        public void RegisterButton(int keyID)
        {
            keys.Add(keyID);
        }
        public void UnRegisterButton(int keyID)
        {
            keys.Remove(keyID);
        }

        //输入的优先级应该安排在很高
        public const int InputEventSystemPriority = 10000;
        public int Priority => InputEventSystemPriority;

        public override void Init()
        {
            base.Init();
            ActionSystemManager.Instance.AddBeforeSync(this);
        }

        public void UpdateLogic(float fixedUpdate)
        {
            if(input!=null)
            {
                //讲按钮事件传递给reader
                foreach (var k in keys)
                {
                    //传递事件
                    var arg = InputEventArgs.Create();
                    arg.data = input.ReadKey(k);
                    eventSystem.RaiseEvent(InputEventArgs.EventID, arg);
                }
            }
            eventSystem.Invoke();
        }


        public void RegisterListener(IEvent handler)
        {
            eventSystem.RegisterListener(InputEventArgs.EventID,handler);
        }
        public void UnRegisterListenser(IEvent handler)
        {
            eventSystem.UnRegisterListenser(InputEventArgs.EventID, handler);
        }
    }
    
}


